<template>
  <div class="container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>学生管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 分页查询 -->
      <el-row :gutter="20">
        <el-col :span="22">
          <el-form :inline="true">
            <el-form-item>
              <el-input v-model="queryInfo.studentName" placeholder="学生姓名" />
            </el-form-item>
            <el-form-item>
              <el-input v-model="queryInfo.studentNum" placeholder="学生校号" />
            </el-form-item>
            <el-form-item>
              <el-input v-model="queryInfo.department" placeholder="学生所在院系" />
            </el-form-item>
            <el-form-item>
              <el-input v-model="queryInfo.classes" placeholder="学生所在班级" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="getStudentList()">查询</el-button>
              <el-button type="primary" icon="el-icon-refresh" @click="resetSearch()">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="2">
          <el-button type="success" @click="addDialogVisible = true">添加学生</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="studentName"></el-table-column>
        <el-table-column label="校号" prop="studentNum"></el-table-column>
        <el-table-column label="院系" prop="department"></el-table-column>
        <el-table-column label="班级" prop="classes"></el-table-column>
        <el-table-column label="一卡通状态" prop="cardStatus">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-tag v-show="!scope.row.cardStatus && !scope.row.tag" type="info">未申请</el-tag>
            <el-tag v-show="!scope.row.cardStatus && scope.row.tag == 1" type="primary">待审核</el-tag>
            <el-tag v-show="scope.row.cardStatus == 1 && !scope.row.tag" type="success">正常</el-tag>
            <el-tag v-show="scope.row.cardStatus == 2 && !scope.row.tag" type="danger">已挂失</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改用户信息" placement="top">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除用户" placement="top">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-delete"
                @click="removeStudent(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.pageIndex"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="this.pageSize"
        :total="this.total"
        layout="total, sizes, prev, pager, next, jumper"
      >
        <!-- :total="100" -->
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加学生" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
        <!-- 表单 -->
        <el-form ref="addFormRef" :rules="addFormRules" :model="addForm" label-width="80px">
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="addForm.studentName"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-input v-model="addForm.sex"></el-input>
          </el-form-item>
          <el-form-item label="校号" prop="studentNum">
            <el-input v-model="addForm.studentNum"></el-input>
          </el-form-item>
          <el-form-item label="宿舍号" prop="dormitoryNum">
            <el-input v-model="addForm.dormitoryNum"></el-input>
          </el-form-item>
          <el-form-item label="院系" prop="department">
            <el-input v-model="addForm.department"></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="classes">
            <el-input v-model="addForm.classes"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="studentPhone">
            <el-input v-model="addForm.studentPhone"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addStudent">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog title="修改学生信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
        <el-form :model="editForm" label-width="80px" ref="editFormRef" :rules="editFormRules">
          <el-form-item label="学生姓名">
            <el-input disabled v-model="editForm.studentName"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-input disabled v-model="editForm.sex"></el-input>
          </el-form-item>
          <el-form-item label="校号">
            <el-input disabled v-model="editForm.studentNum"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="院系" prop="department">
            <el-input v-model="editForm.department"></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="classes">
            <el-input v-model="editForm.classes"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="studentPhone">
            <el-input v-model="editForm.studentPhone"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editStudent">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import commonServe from '../../api/services/common.serve'
export default {
  data() {
    // 验证手机号的正则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    // 验证性别
    var checkSex = (rule, value, cb) => {
      const regSex = /^[男|女]{1}$/
      if (regSex.test(value)) {
        return cb()
      }
      cb(new Error('请输入男或女'))
    }
    // 验证校号
    var checkStudentNum = (rule, value, cb) => {
      const regStudentNum = /^\d{7}$/
      if (regStudentNum.test(value)) {
        return cb()
      }
      cb(new Error('校号为7位数字'))
    }
    return {
      userList: [],
      pageSize: 10,
      pageIndex: 1,
      queryInfo: {},
      total: 0,
      addDialogVisible: false, //添加用户对话框
      editDialogVisible: false, //修改用户对话框
      editCardDialogVisible: false, //变更一卡通状态
      //添加用户
      addForm: {
        studentName: '',
        sex: '',
        studentNum: '',
        dormitoryNum: '',
        department: '',
        classes: '',
        studentPhone: ''
      },
      //添加用户验证规则
      addFormRules: {
        studentName: [
          { required: true, message: '请输入学生姓名', trigger: 'blur' },
          { min: 1, max: 12, message: '用户名长度在1-12字符之间', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请输入性别', trigger: 'blur' },
          { validator: checkSex, trigger: 'blur' }
        ],
        studentNum: [
          { required: true, message: '请输入学生学号', trigger: 'blur' },
          { validator: checkStudentNum, trigger: 'blur' }
        ],
        dormitoryNum: [{ required: true, message: '请输入学生宿舍号', trigger: 'blur' }],
        department: [{ required: true, message: '请输入学生院系', trigger: 'blur' }],
        classes: [{ required: true, message: '请输入学生班级', trigger: 'blur' }],
        studentPhone: [
          { required: true, message: '请输入学生手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 查询到的用户信息
      editForm: {},
      // 修改用户表单验证规则
      editFormRules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在6-15字符之间', trigger: 'blur' }
        ],
        department: [{ required: true, message: '请输入学生所在院系', trigger: 'blur' }],
        classes: [{ required: true, message: '请输入学生所在班级', trigger: 'blur' }],
        studentPhone: [{ required: true, message: '请输入学生手机号', trigger: 'blur' }, { validator: checkMobile }]
      }
    }
  },
  created() {
    this.getStudentList()
  },
  methods: {
    // 获取学生列表
    getStudentList() {
      commonServe
        .getAllStudentList(this.pageIndex, this.pageSize, this.queryInfo)
        .then((res) => {
          console.log(res)
          if (res.code === 200) {
            // this.$message.success('获取学生信息成功')
            this.userList = res.data.list
            this.total = res.data.total
          } else {
            this.$message.warning('获取学生信息失败，请刷新重试')
          }
        })
        .catch((err) => {
          this.$message.warning(err.message || '获取学生信息失败，请刷新重试')
        })
    },
    // 重置查询表单
    resetSearch() {
      this.queryInfo = {}
      this.getStudentList()
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.pageSize = newSize
      this.getStudentList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.pageIndex = newPage
      this.getStudentList()
    },
    // 添加用户对话框关闭，清空表单
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    //添加学生
    addStudent() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return
        commonServe
          .addStudent(this.addForm)
          .then((res) => {
            console.log(res)
            if (res.code === 200) {
              this.$message.success('添加成功' || res.message)
              this.getStudentList()
            } else {
              this.$message.warning(res.message)
            }
          })
          .catch((err) => {
            this.$message.warning(err.message)
          })
      })
      this.addDialogVisible = false
    },
    // 修改学生信息对话框
    showEditDialog(val) {
      this.editDialogVisible = true
      console.log(val)
      commonServe
        .getStudentInfo(val)
        .then((res) => {
          console.log(res)
          if (res.code === 200) {
            this.editForm = res.data.student
          } else {
            this.$message.warning('获取学生信息失败')
          }
        })
        .catch((err) => {
          this.$message.warning(err.message)
        })
    },
    // 修改学生信息
    editStudent() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return
      })
      console.log(this.editForm.id)
      // 请求接口
      commonServe
        .changeStudentInfo(this.editForm.id, this.editForm)
        .then((res) => {
          console.log(res)
          if (res.code === 200) {
            // 关闭列表
            this.editDialogVisible = false
            // 刷新数据
            this.getStudentList()
            this.$message.success('修改成功')
          } else {
            this.$message.warning('修改失败')
          }
        })
        .catch((err) => {
          this.$message.warning(err.message)
        })
    },
    // 修改用户对话框关闭
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除用户
    async removeStudent(val) {
      console.log(val)
      const confirmResult = await this.$confirm('此操作将永久删除该学生, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      // 点击确认返回字符串confirm
      // 点击取消返回字符串cancel
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除用户')
      }
      // 调用接口删除用户
      commonServe
        .removeStudentById(val)
        .then((res) => {
          console.log(res)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getStudentList()
          } else {
            this.$message.warning('删除失败')
          }
        })
        .catch((err) => {
          this.$message.warning(err.message)
        })
    }
  }
}
</script>

<style lang="less" scoped>
.el-input.is-disabled /deep/ .el-input__inner {
  color: #606266;
}
</style>
